package com.heima.web.action;

import java.io.IOException;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.heima.domain.User;
import com.heima.serviceInterface.IUserService;
import com.heima.tools.SessionUtils;

@Controller
@Scope("prototype")
public class UserAction extends BaseAction<User> {
	private String checkcode;
	@Resource
	private IUserService userService;

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	// 登录
	public String login() {
		String code = (String) SessionUtils.getSession().getAttribute("key");
		if (code == null) {
			return "login";
		} else if (StringUtils.isBlank(checkcode) || !checkcode.equals(code)) {
			this.addActionError(this.getText("checkerror"));
			return "login";
		} else {
			User user = userService.login(model);
			if (model == null || user == null) {
				this.addActionError(this.getText("usererror"));
				return "login";
			} else {
				SessionUtils.getSession().setAttribute("user", user);
				return "index";
			}
		}
	}

	// 退出
	public String exit() {
		SessionUtils.getSession().invalidate();
		return "login";
	}

	public String edit() {
		try {
			userService.edit(model);
			ServletActionContext.getResponse().getWriter().print(1);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		return NONE;
	}
}
